import { setList } from "@/store/modules/category";
import { useAxiosWithAuth } from "@/utils/useAxiosWidthAuth";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";

// 首页头部分类
export const useAllCategory = function () {
  const axios = useAxiosWithAuth();
  const dispatch = useDispatch();

  useEffect(() => {
    async function login() {
      const res: any = await axios({
        method: "get",
        url: "/home/category/head",
      });

      dispatch(setList(res.result));
    }

    login();
  }, [dispatch]);
};

// 拿到二级类目
export const useFindTopCategory = (id: string) => {
  const axios = useAxiosWithAuth();
  const [subList, setsubList] = useState<any[]>([]);
  useEffect(() => {
    async function findTopCategory() {
      const res: any = await axios({
        method: "get",
        url: "/category",
        params: { id },
      });
      setsubList(res.result.children);
    }
    findTopCategory();

    // 路由改变后滚动到顶部
    window.scrollTo(0, 0);
  }, [id]);
  return subList;
};

/**
 * 获取二级分类筛选条件数据
 * @param {String} id - 二级分类ID
 */
export const useSubCategoryFilter = (id: string) => {
  const axios = useAxiosWithAuth();
  const [subListFilter, setsubList] = useState<any[]>([]);
  useEffect(() => {
    async function findSubCategoryFilter() {
      const res: any = await axios({
        method: "get",
        url: "/category/sub/filter",
        params: { id },
      });
      res.result.brands.selectBrand = null;
      res.result.brands.unshift({ id: null, name: "全部" });
      res.result.saleProperties.forEach((p: any) => {
        p.selectedProp = null;
        p.properties.unshift({ id: null, name: "全部" });
      });
      setsubList(res.result);
    }
    findSubCategoryFilter();
  }, [id]);

  const updateBrand = (brandId: number) => {
    setsubList((prevData: any) => {
      prevData.brands["selectBrand"] = brandId;
      return { ...prevData };
    });
  };
  const updateSaleProperties = (saleId: number, index: number) => {
    setsubList((prevData: any) => {
      prevData.saleProperties[index].selectedProp = saleId;
      return { ...prevData };
    });
  };
  return { subListFilter, updateBrand, updateSaleProperties };
};
